import Vue from 'vue'
import {
  baseService,
  arrayTools
} from '@/service/common/baseService'
import tools from '@/service/common/tools'
import formValidator from '@/service/form/formValidator'
import formServiceExtend from './formServiceExtend'

import abCheckbox from '@/components/form/abCheckbox.vue'
import abDict from '@/components/form/abDict.vue'
import abDesensitize from '@/components/form/abDesensitize.vue'

Vue.component('abCheckbox', abCheckbox);
Vue.component('abDict', abDict);
Vue.component('abDesensitize', abDesensitize);
import AbDate from '@/components/form/abDate.vue';

Vue.component('abDate', AbDate);
import abTimeliness from '@/components/form/abTimeliness.vue';

Vue.component('abTimeliness', abTimeliness);
// 生僻字录入
import abCharacters from "@/components/form/abCharacters"

Vue.component('abCharacters', abCharacters)

import AbUpload from '@/components/form/abUpload.vue';

Vue.component('abUpload', AbUpload);
import {
  Datetime
} from 'vux'

Vue.component('datetime', Datetime)
import AbSubAdd from '@/components/form/abSubAdd.vue';

Vue.component('abSubAdd', AbSubAdd);

import abDynamicSelect from '../../components/form/abDynamicSelect.vue'

Vue.component('abDynamicSelect', abDynamicSelect);

import abSerialNo from '@/components/form/abSerialNo.vue';

Vue.component('abSerialNo', abSerialNo);

import aSignature from '@/components/form/ab-signature.vue';

Vue.component('abSignature', aSignature);

import abScanCode from '@/components/form/abScanCode.vue';

Vue.component('abScanCode', abScanCode);

import abNumber from '@/components/form/abNumber.vue';

Vue.component('abNumber', abNumber);
//流程引用
import abFlowQuote from '@/components/form/ab-flow-quote.vue';

Vue.component('abFlowQuote', abFlowQuote);

//表单意见控件
import abOpinion from '@/components/form/abOpinion.vue';

Vue.component('abOpinion', abOpinion);

//表单用户常用意见组件
import abUsefulOpinion from '@/components/form/abUsefulOpinion.vue';

Vue.component('abUsefulOpinion', abUsefulOpinion);

//行政区域组件
import abRegion from '@/components/form/abRegion.vue';

Vue.component('abRegion', abRegion);

import abCustQuery from '../../components/form/abCustQuery.js'

Vue.directive('abCustQuery', abCustQuery);

import gzShareLink from "../../components/form/gz-shareLink";

Vue.component('gzShareLink', gzShareLink)

import sendVerificationCode from "../../components/form/sendVerificationCode";

Vue.component('sendVerificationCode', sendVerificationCode)

//签名
import canvasSignname from "../../components/form/canvasSignname";

Vue.component('canvasSignname', canvasSignname)
//合约状态
import adoptStatus from "../../components/customize/adoptStatus";

Vue.component('adoptStatus', adoptStatus)

//生成借款合同页面
import abLoan from "../../components/customize/ab-loan";

Vue.component('abLoan', abLoan)
//查看还款计划
import tjRepaymentPlan from "../../components/customize/tj-repayment-plan";

Vue.component('tjRepaymentPlan', tjRepaymentPlan)

//还款账户选择
import repaymentAccount from "../../components/customize/repayment-account";

Vue.component('repaymentAccount', repaymentAccount)
//用款 处理结果
import borrowingResults from "../../components/customize/borrowingResults";

Vue.component("borrowingResults", borrowingResults)

//图片上传
import tjUploader from "../../components/customize/tj-uploader";

Vue.component('tjUploader', tjUploader)

//折叠
import abSubCollapse from "../../components/form/ab-sub-collapse";

Vue.component("abSubCollapse", abSubCollapse)

//授权状态
import creditAuthorizationResults from "../../components/customize/creditAuthorizationResults";

Vue.component("creditAuthorizationResults", creditAuthorizationResults)

// 省市区联动选择
import abDynamicAreaSelect from '../../components/form/abDynamicAreaSelect.vue'
Vue.component('abDynamicAreaSelect', abDynamicAreaSelect);

//申请成功
import sqStatus from "../../components/customize/sqStatus";
Vue.component("sqStatus",sqStatus)

import abTextarea from "../../components/form/ab-textarea";
Vue.component('abTextarea',abTextarea)

/**
 * 自定义组件：
 * OCR上传组件
 * 人脸识别
 * input输入框
 * 按钮
 * 复选框
 * 日期选择器
 * 图片上传
 * picker选择器
 * 地址选择器
 * 单选框
 */

import {
  OCRUpload,
  gzFaceVerification,
  gzFaceVerificationOld,
  gzInput,
  gzButton,
  gzChecker,
  gzDate,
  gzImgUpload,
  gzPicker,
  gzPickerAddress,
  gzRadio,
  gzAuthorization,
  gzCodeInput,
  gzAdopt,
  gzRefuse,
  gzPunchList,
  gzProductDispose,
  gzRouteProp,
  gzClockIn
} from '@/components/customize'

Vue.component('ocrUpload', OCRUpload);
Vue.component('gzFaceVerification', gzFaceVerification);
Vue.component('gzInput', gzInput);
Vue.component('gzButton', gzButton);
Vue.component('gzChecker', gzChecker);
Vue.component('gzDate', gzDate);
Vue.component('gzImgUpload', gzImgUpload);
Vue.component('gzPicker', gzPicker);
Vue.component('gzAddress', gzPickerAddress);
Vue.component('gzRadio', gzRadio);
Vue.component('gzAuthorization', gzAuthorization);
Vue.component('gzFaceVerificationOld', gzFaceVerificationOld);
Vue.component('gzCodeInput', gzCodeInput);
Vue.component('gzAdopt', gzAdopt);
Vue.component('gzRefuse', gzRefuse);
Vue.component('gzPunchList', gzPunchList);
Vue.component('gzProductDispose', gzProductDispose);
Vue.component('gzRouteProp', gzRouteProp);
Vue.component('gzClockIn', gzClockIn);


var FormService = {};
/**
 * 混入html中的组件定义的参数变量
 */
FormService.initCustFormFu = function (html, data) {
  // 流程那里 url 表单不处理
  if (data.form && data.form.type !== "INNER") return;

  window.custFormComponentMixin = {};
  var custComponentData = data;

  // 处理 custFormComponentMixin
  if (html.indexOf("<script>") != -1) {
    var reg = /<script[^>]*?>[\s\S]*?<\/script>/i;
    var patten = reg.exec(html)
    var script = patten[0];

    var len1 = script.indexOf(">")
    var len2 = script.lastIndexOf("<")
    var custScriptStr = script.substring(len1 + 1, len2);
    html = html.replace(reg, "");

    if (custScriptStr) {
      try {
        // TODO严格模式下问题
        eval(custScriptStr.substring(custScriptStr.indexOf("window.custFormComponentMixin"))); // eslint-disable-line
      } catch (e) {
        console.error("解析表单脚本异常", custScriptStr, e);
      }
    }

    // 用于第三层子表数据暂存 _temp.xxx = [] //则该子表的数据暂存
    custComponentData.subTempData = {};
    // 三层子表对话框的展示 _subTable.xxx = true;//则弹框中
    custComponentData.subTableDialog = {};
  }


  /**
   * 公共的常用 表单 js
   */
  var custFormMethods = {
    abGetNumber: function (data) {
      if (data === undefined || data === "") {
        return 0;
      }
      var number = Number(data);
      if (number === NaN) {
        console.info("计算对象中存在 NaN");
        return 0;
      }
      return number;
    },
    abSubAvg: function (subDataList, key) {
      if (!subDataList || !key || subDataList.length == 0) {
        return "not calculate";
      }
      var sum = 0;
      subDataList.forEach(function (data) {
        if (!data[key]) return;
        sum = sum + Number(data[key]);
      })
      return sum / subDataList.length;
    },
    abSubSum: function (subDataList, key) {
      if (!subDataList || !key || subDataList.length == 0) {
        return "not calculate";
      }
      var sum = 0;
      subDataList.forEach(function (data) {
        if (!data[key]) return;
        sum = sum + Number(data[key]);
      })
      return sum;
    },
    // 展示子表 TODO 改成组件 而不是subTempadata，subTableDialog这种，并添加确认框
    showSubTable: function (dataScope, tableName) {
      if (!dataScope[tableName + "List"]) {
        this.$set(dataScope, tableName + "List", []);
      }

      this.$set(this.subTempData, tableName + "List", dataScope[tableName + "List"]);
      this.$set(this.subTableDialog, tableName, true);
    }
  }

  Vue.component('ab-custom-form', {
    name: "customForm",
    mixins: [custFormComponentMixin],
    template: html,
    data: function () {
      return custComponentData;
    },
    methods: custFormMethods
  });
};


/**
 * <pre>
 * 表单增加子表指令
 * abSubAdd: 为一个list push 一个对象
 * Arr{0] = list
 * Arr[1] = object
 * 会将 object extends 然后push 到 list 中
 * </pre>
 */
Vue.directive('SubAdd', {
  bind: function (el, binding, vnode) {
    initEmptySub(binding, vnode);

    addEvent(el, 'click', function (e) {
      if (binding.value && binding.value.length == 2) {
        binding.value[0].push(Vue.tools.extend(binding.value[1]));
      }
    });
  }
})

Vue.directive('SubDel', {
  inserted: function (el, binding) {
    $(el).off("click");
    $(el).on("click", function (e) {
      if (binding.value && binding.value.length == 2) {
        arrayTools.del(binding.value[1], binding.value[0]);
      }
    });
  },
  update: function (el, binding) {
    $(el).off("click");
    $(el).on("click", function (e) {
      if (binding.value && binding.value.length == 2) {
        arrayTools.del(binding.value[1], binding.value[0]);
      }
    });
  },
})

function initEmptySub(binding, vnode) {
  if (!binding.value && binding.value.length !== 2) {
    return;
  }
  if (binding.value[0]) return;
  //[data.applyOrderInfo.customerRelList,initData.applyOrderInfo.customerRel]
  //取出data.applyOrderInfo.customerRelList
  var dataPath = binding.expression.split(",")[0].substring(1);
  var index = dataPath.lastIndexOf(".");
  var tableKey = dataPath.substring(index + 1);
  var prePath = dataPath.substring(0, index);

  binding.value[0] = [];
  eval("vnode.context.$set(vnode.context." + prePath + ",\"" + tableKey + "\",binding.value[0])");
  return;

  var scope = vnode.context;

  for (var i = 0; i < array.length; i++) {
    if (i == array.lenght)
      scope = scope[array[i]];
  }

  for (var i = 0, k; k = array[i++];) {
    scope = scope[k];
  }
  return value;

}


/**
 * 校验,依赖 v-model 或者 组件的 input 事件
 *
 */
Vue.directive("AbValidate", {
  inserted: function (el, binding, vnode) {
    formValidator.doValidate(el, binding, vnode);
    var validateHandler = function (e) {
      if (e.target && e.target !== el) return;

      var value = e.target ? e.target.value : e;
      formValidator.doValidate(el, binding, vnode, value);
    }

    if (vnode.componentInstance) {
      vnode.componentInstance.$on("input", function (value) {
        validateHandler(value);
      })
    } else {
      // addEvent(el, 'input', validateHandler);
    }
  },
  update: function (el, binding, vnode, oldVnode) {
    if (el.value === undefined && !vnode.data && !vnode.data.model && !vnode.data.model.val) return;

    var value = el.value;
    if (vnode.data && vnode.data.model && vnode.data.model.value) {
      value = vnode.data.model.value;
    }
    var oldValue = vnode.elm.$_oldValue;
    if (oldValue !== value || el.type === "radio") {
      formValidator.doValidate(el, binding, vnode, value);
    }
    vnode.elm.$_oldValue = value;
  },
  unbind: function (el, binding, vnode) {
    if (vnode.context.$validity[vnode.data.attrs.desc]) {
      delete vnode.context.$validity[vnode.data.attrs.desc];
    }
  }

})

/**
 * 获取表单的校验情况
 * 自定义表单为<custForm> 组件。当前componentScope 为页面的scope
 * 所以要先找到 custForm 组件的作用域
 * return
 */
FormService.getValidateMsg = function (componentScope) {
  var errorStr = "";
  if (!componentScope.$validity) {
    return errorStr;
  }

  for (var key in componentScope.$validity) {
    if (errorStr) {
      errorStr = errorStr + "<br/>"
    }
    errorStr = errorStr + "【" + key + "】" + "：" + componentScope.$validity[key];
  }

  if (errorStr) {
    errorStr = "<div style='text-align:left'>" + errorStr + "</div>"
  }

  return errorStr;
}

/**
 * 获取表单的校验情况(单条提示)
 * 自定义表单为<custForm> 组件。当前componentScope 为页面的scope
 * 所以要先找到 custForm 组件的作用域
 * return
 */
FormService.getValidateOnlyMsg = function (componentScope) {
  var errorStr = "";
  if (!componentScope.$validity) {
    return errorStr;
  }
  let errorArr = []
  for (var key in componentScope.$validity) {
    // if(errorStr){errorStr = errorStr + "<br/>"}
    errorStr = componentScope.$validity[key];
    errorArr.push(errorStr)
  }

  // if(errorStr){
  // 	errorStr = "<div style='text-align:left'>"+errorStr+"</div>"
  // }

  return errorArr[0];
}


/**
 *  基础权限，对控件做只读、必填、无权限, @v-model 必须
 *  v-ab-permission="permission.kjcs.cskj.xb" v-model=""
 *
 *  判断是否有展示权限，无则移除dom
 *  v-ab-permission:show="permission.kjcs.cskj.xb"
 *
 *   *  判断是否有编辑权限，无则移除dom
 *  v-ab-permission:edit="permission.kjcs.cskj.xb"
 */
Vue.directive("AbPermission", {
  inserted: function (el, binding, vnode) {
    handleElementPermission(el, binding, vnode);
  },
  update: function (el, binding, vnode) {
    handleElementPermission(el, binding, vnode);
  }
})

/**
 * 处理控件权限
 *
 * @param el
 * @param binding
 * @param vnode
 * @returns
 */
function handleElementPermission(el, binding, vnode) {
  if (!binding.value) return;
  // 只成功处理一次
  if (el.dataset.hasInited) return;

  if (binding.arg) {
    handleSpecialPermision(el, binding, vnode);
    // return;
  }

  // 处理必填权限
  if (binding.value == "b") {
    vnode.elm.required = true;
  } else if (binding.value === "w") {

  }
  //
  else if (binding.value === "r") {
    vnode.elm.readOnly = true;
    vnode.elm.disabled = true;
    if (vnode.elm.childNodes) {
      disableChildNodes(vnode.elm, true)
    }
  } else if (binding.value === "n") {
    vnode.elm.remove();
  }

  el.dataset.hasInited = true;
}

//讲子组件全部disable
function disableChildNodes(elm, isReadOnly) {
  if (elm.childNodes) {
    elm.childNodes.forEach(function (child) {
      child.disabled = isReadOnly
      child.readOnly = isReadOnly;
      if (child.childNodes) {
        disableChildNodes(child, isReadOnly)
      }
    })
  }
}

function handleSpecialPermision(el, binding, vnode) {

  //无展示权限则移除掉标签
  if (binding.arg === "show" && binding.value == "n") {
    vnode.elm.remove();
  }

  //无编辑权限则移除掉控件
  if (binding.arg === "edit" && binding.value !== "w" && binding.value !== "b") {
    vnode.elm.remove();
  }

  el.dataset.hasInited = true;
}


function addEvent(element, event, listener) {
  if (element.addEventListener) {
    element.addEventListener(event, listener, false);
  } else if (element.attachEvent) {
    element.attachEvent('on' + event, listener);
  } else {
    element['on' + event] = listener;
  }
}

export default FormService
